package admin

import (
	"context"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductListLogic) ProductList(req *types.ProductListReq) (resp *types.ProductListResp, err error) {
	tx := utils.Db.Model(&models.Product{}).Joins("LEFT JOIN categories ON products.category_id = categories.id")
	if req.Name != "" {
		tx.Where("products.name LIKE ? OR products.description LIKE ? OR products.detail_html LIKE ?", "%"+req.Name+"%", "%"+req.Name+"%", "%"+req.Name+"%")
	}
	if req.IsOnSale != 0 {
		if req.IsOnSale == 10 {
			tx.Where("products.is_on_sale = ?", true)
		} else {
			tx.Where("products.is_on_sale = ?", false)
		}
	}
	if req.CategoryID != 0 {
		tx.Where("products.category_id = ?", req.CategoryID)
	}

	total := utils.TxCount(tx)
	if total == 0 {
		return &types.ProductListResp{
			Total: total,
			List:  []types.ProductListRespItem{},
		}, nil
	}
	tx = tx.Select("products.*,categories.name as category_name").Order("products.id desc")
	datas := make([]types.ProductListRespItem, 0)
	utils.TxPage(tx, req.Page, &datas)
	return &types.ProductListResp{
		Total: total,
		List:  datas,
	}, nil
}
